﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace CitUlsViewer
{
    public enum UlsType
    {
        OpenedFile,
        Uls
    }

    public partial class formMain : Form
    {
        string _openedFileName;

        private string OpenedFileName
        {
            get
            {
                return _openedFileName;
            }
            set
            {
                _openedFileName = value;
                lbstFileName.Text = _openedFileName;
            }
        }
        private UlsType OpenType { get; set; }

        public formMain()
        {
            InitializeComponent();
        }

        private void AbrirUlsAntigo()
        {
            openFile.InitialDirectory = Constants.LOG_FOLDER;

            if (openFile.ShowDialog() == DialogResult.OK)
            {
                this.OpenedFileName = openFile.FileName;

                DataTable dt = LogParser.FillDataTable(this.OpenedFileName);

                CarregarLog(dt);

                this.OpenType = UlsType.Uls;
            }
        }

        private void AdicionarLogAoExistente()
        {
            openFile.InitialDirectory = Constants.LOG_FOLDER;

            if (openFile.ShowDialog() == DialogResult.OK)
            {
                this.OpenedFileName = openFile.FileName;

                DataTable dtOwner = grid.DataSource as DataTable;
                DataTable dt = LogParser.FillDataTable(this.OpenedFileName);

                dtOwner.Merge(dt);

                CarregarLog(dtOwner);

                this.OpenType = UlsType.Uls;
            }
        }

        private void AbrirUlsAtual()
        {
            this.OpenedFileName = LogParser.GetLastUlsFile(Constants.LOG_FOLDER);

            DataTable dt = LogParser.FillDataTable(this.OpenedFileName);

            CarregarLog(dt);

            this.OpenType = UlsType.OpenedFile;
        }

        private void CarregarLog(DataTable dt)
        {
            grid.DataSource = dt;

            CarregaCategory(dt);
            CarregaLevel(dt);
        }

        private void CarregaLevel(DataTable dt)
        {
            var query = dt.AsEnumerable().Select(c => new { Level = c.Field<string>("Level") }).OrderBy(c => c.Level);

            cblLevel.Items.Clear();
            foreach (var item in query.Distinct())
            {
                cblLevel.Items.Add(item.Level);
            }
        }

        private void CarregaCategory(DataTable dt)
        {
            var query = dt.AsEnumerable().Select(c => new { Category = c.Field<string>("Category") }).OrderBy(c => c.Category);

            cblCategory.Items.Clear();
            foreach (var item in query.Distinct())
            {
                cblCategory.Items.Add(item.Category);
            }
        }

        private void sairToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private string GetLevelFilter()
        {
            string level = string.Empty;

            foreach (object item in cblLevel.CheckedItems)
            {
                if (!String.IsNullOrEmpty(level))
                    level += ",";
                level += "'" + item.ToString() + "'";
            }

            return (String.IsNullOrWhiteSpace(level)) ? string.Empty : string.Format("Level IN ({0})", level);
        }

        private string GetCategoryFilter()
        {
            string category = string.Empty;

            foreach (object item in cblCategory.CheckedItems)
            {
                if (!String.IsNullOrEmpty(category))
                    category += ",";
                category += "'" + item.ToString() + "'";
            }

            return (String.IsNullOrWhiteSpace(category)) ? string.Empty : string.Format("Category IN ({0})", category);
        }

        private void btnFilter_Click(object sender, EventArgs e)
        {
            List<string> filter = new List<string>();

            string level = this.GetLevelFilter();
            string category = this.GetCategoryFilter();

            if (!String.IsNullOrWhiteSpace(level))
                filter.Add(level);
            if (!String.IsNullOrWhiteSpace(category))
                filter.Add(category);
            if (!String.IsNullOrWhiteSpace(txtCorrelationId.Text))
                filter.Add(String.Format("CorrelationId = '{0}'", txtCorrelationId.Text));
            if (!String.IsNullOrWhiteSpace(txtFilterMessage.Text))
                filter.Add(String.Format("Message LIKE '%{0}%'", txtFilterMessage.Text));

            DataView dv = (grid.DataSource as DataTable).DefaultView;

            dv.RowFilter = string.Join(" AND ", filter.ToArray());
        }

        private void grid_SelectionChanged(object sender, EventArgs e)
        {
            if (grid.SelectedRows.Count > 0)
            {
                txtMessage.Text = grid.SelectedRows[0].Cells[7].Value.ToString();
            }
        }

        private void uLSAtualToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AbrirUlsAtual();
        }

        private void arquivoAntigoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AbrirUlsAntigo();
        }

        private void sobreToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string mensagem = "CI&T ULS Log Viewer\n\nFerramenta auxiliar para análise dos arquivos de log do Sharepoint.\n\nDesenvolvido por Daniel Santana Rodrigues.\ndaniel.santana@gmail.com";
            MessageBox.Show(mensagem, "Sobre", MessageBoxButtons.OK);
        }

        private void adicionarLogAoAtualToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AdicionarLogAoExistente();
        }

        private void btnLimpar_Click(object sender, EventArgs e)
        {
            LimparFiltroRapido();
        }

        private void LimparFiltroRapido()
        {
            for (int i = 0; i < cblCategory.Items.Count; i++)
                cblCategory.SetItemChecked(i, false);
            for (int i = 0; i < cblLevel.Items.Count; i++)
                cblLevel.SetItemChecked(i, false);

            txtCorrelationId.Text = string.Empty;
            txtFilterMessage.Text = string.Empty;
            txtMessage.Text = string.Empty;

            DataView dv = (grid.DataSource as DataTable).DefaultView;
            dv.RowFilter = string.Empty;
        }

        private void grid_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            lbstRowCount.Text = String.Format("{0} linhas", grid.RowCount);
        }
    }
}
